<template>
  <div id="department_create">
    <div class="Row_content">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="90">
        <FormItem label="上级组织："
                  prop="parentId">
          <treeselect :options="options"
                      @select="selectList"
                      :normalizer="normalizer"
                      noResultsText="未搜索符合的上级组织"
                      noOptionsText="上级组织为空"
                      placeholder="请输入上级组织"
                      v-model='formValidate.parentId' />
        </FormItem>
        <FormItem label="组织名称："
                  prop="orgName">
          <Input v-model="formValidate.orgName"
                 placeholder="请输入组织名称"
                 :maxlength='20'
                 @on-keyup='filterSpace'></Input>
        </FormItem>
        <FormItem label="组织编码："
                  prop="orgCode">
          <Input v-model="formValidate.orgCode"
                 placeholder="请输入组织编码"
                 :maxlength='50'
                 @on-keyup='filterSpace'></Input>
        </FormItem>
        <FormItem label="组织标签：" prop="groupTagIdList">
          <Select v-model="formValidate.groupTagIdList" filterable :clearable='true'>
            <Option v-for="item in orgTags" :value="item.id" :key="item.id">{{ item.tagName }}</Option>
          </Select>
        </FormItem>
        <FormItem label="排序号："
                  prop="sortNum">
          <Input v-model="formValidate.sortNum"
                 placeholder="请输入数字"
                 :maxlength='4'
                 @on-blur="priceBlur"
                 @on-keyup='keyUp'></Input>
        </FormItem>
        <FormItem label="组织描述："
                  prop="remark"
                  style="margin-bottom:0px">
          <div class="desc-oranizate">
            <Input v-model="formValidate.remark"
                   type="textarea"
                   :maxlength='300'
                   :autosize="{minRows: 4,maxRows: 8}"
                   placeholder="请输入组织描述"
                   ref="textarea"></Input>
            <span class="rol_tipsd">{{desCount}}/300</span>
          </div>
        </FormItem>
        <FormItem label="组织类型："
                  prop="orgType">
          <!-- <RadioGroup v-model="formValidate.orgType"
                      size="large">
            <Radio label="1">是</Radio>
            <Radio label="0"
                   style="margin-left:50px">否</Radio>
          </RadioGroup> -->
          <Select v-model="formValidate.orgType" class="select-shop-item">
            <Option v-for="(item, i) in orgList" :value="item.value" :key="i">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem class="form-btn">
          <Button type="primary"
                  style="width:80px"
                  :disabled="isDisabled"
                  @click='submit'>确定</Button>
          <Button style="width:80px;margin-left:20px;"
                  @click="cancel">取消</Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
import { routeEqual } from '@/libs/util'
import { getOrgAllTree, saveOrg, getOrgDetail, updateOrg, getOrgTag } from '@/api/system/org'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'organization_create',
  components: { Treeselect },
  data () {
    return {
      orgList: [
        { value: '0', label: '职能部门' },
        { value: '1', label: '门店' },
        { value: '2', label: '区域' },
        { value: '3', label: '片区' },
        { value: '4', label: '总部' }
      ],
      name: '添加部门',
      options: [],
      isDisabled: false,
      normalizer (node) {
        if (node.childList) {
          if (node.childList.length > 0) {
            return {
              id: node.id,
              label: node.orgName,
              children: node.childList
            }
          } else {
            return {
              id: node.id,
              label: node.orgName
            }
          }
        }
      },
      formValidate: {
        parentId: null,
        orgName: '',
        orgCode: '',
        groupTagIdList: '',
        remark: '',
        sortNum: '',
        orgType: '0' // 1表示门店，0表示组织
      },
      ruleValidate: {
        parentId: [{ required: true, message: '上级组织不能为空', trigger: 'blur' }],
        orgName: { required: true, message: '组织名称不能为空' },
        sortNum: [{ required: true, message: '排序号不能为空', trigger: 'blur' }],
        orgType: [{ required: true, message: '请选择是否为门店', trigger: 'blur' }]
      }
    }
  },
  methods: {
    selectList (data) {
      this.formValidate.parentId = data.id
      // this.$refs.formValidate.validate((valid) => { })
      this.$refs.formValidate.validateField('parentId', (valid) => { })
    },
    priceBlur () {
      this.formValidate.sortNum = this.formValidate.sortNum.replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
    },
    keyUp () {
      this.formValidate.sortNum = this.formValidate.sortNum.replace(/[^\d]/g, '').replace(/^0{1,}/g, '')
    },
    filterSpace () {
      this.formValidate.orgName = this.formValidate.orgName.replace(/\s+/g, '')
      this.formValidate.orgCode = this.formValidate.orgCode.replace(/\s+/g, '')
    },
    closeModal () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'organization_list'
        })
      })
    },
    // 获取标签列表
    getOrgTag () {
      getOrgTag({
        merchantId: this.$store.state.user.merchantId,
        status: 1
      }).then(res => {
        if (res.data.status === 200) {
          this.orgTags = res.data.data || []
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    },
    submit () {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          this.formValidate.orgName = this.formValidate.orgName.replace(/\s*/g, '')
          let data = { ...this.formValidate, 'merchantId': this.$store.state.user.merchantId }
          data.orgType = Number(data.orgType)
          data.sortNum = Number(data.sortNum)
          data.groupTagIdList = data.groupTagIdList ? [data.groupTagIdList] : []
          if (!this.isDisabled) {
            if (this.isDisabled) {
              return
            }
            if (this.$route.params.id) {
              updateOrg({ ...data, id: this.$route.params.id }).then(res => {
                setTimeout(() => {
                  this.isDisabled = false
                }, 500)
                if (res.data.status === 200) {
                  this.$Message.success('编辑成功！')
                  this.closeModal()
                } else {
                  this.$Message.error(`${res.data.error}`)
                }
              })
            } else {
              saveOrg(data).then(res => {
                setTimeout(() => {
                  this.isDisabled = false
                }, 500)
                if (res.data.status === 200) {
                  this.$Message.success('新增成功！')
                  this.closeModal()
                } else {
                  this.$Message.error(`${res.data.error}`)
                }
              })
            }
          }
        }
      })
    },
    cancel () {
      this.$refs.formValidate.resetFields()
      this.closeModal()
    }
  },
  computed: {
    desCount () {
      if (this.formValidate.remark) {
        return this.formValidate.remark.length
      } else {
        return 0
      }
    }
  },
  mounted () {
    this.$refs.formValidate.resetFields()
    getOrgAllTree({ 'merchantId': this.$store.state.user.merchantId, 'orgType': 0, status: 1 }).then(res => {
      if (res.data.status === 200) {
        this.options.push(res.data.data)
      } else {
        this.$Message.error(`${res.data.error}`)
      }
    })
    this.getOrgTag()
    if (this.$route.params.id) {
      getOrgDetail({ 'merchantId': this.$store.state.user.merchantId, id: this.$route.params.id }).then(res => {
        if (res.data.status === 200) {
          this.formValidate = {
            parentId: res.data.data.parentId,
            orgName: res.data.data.orgName,
            remark: res.data.data.remark,
            sortNum: String(res.data.data.sortNum),
            orgType: String(res.data.data.orgType)
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    }
  }
}
</script>
<style lang="less">
</style>
